/*
 *  sha1_hash.cpp
 *
 *  Description:
 *      This file implements the Secure Hashing Algorithm 1 as
 *      defined in FIPS PUB 180-1 published April 17, 1995.
 *
 *      The SHA-1, produces a 160-bit message digest for a given
 *      data stream.  It should take about 2**n steps to find a
 *      message with the same digest as a given message and
 *      2**(n/2) to find any two messages with the same digest,
 *      when n is the digest size in bits.  Therefore, this
 *      algorithm can serve as a means of providing a
 *      "fingerprint" for a message.
 *
 *  Portability Issues:
 *      SHA-1 is defined in terms of 32-bit "words".  This code
 *      uses <stdint.h> (included via "sha1.hpp" to define 32 and 8
 *      bit unsigned integer types.  If your C compiler does not
 *      support 32 bit unsigned integers, this code is not
 *      appropriate.
 *
 *  Caveats:
 *      SHA-1 is designed to work with messages less than 2^64 bits
 *      long.  Although SHA-1 allows a message digest to be generated
 *      for messages of any number of bits less than 2^64, this
 *      implementation only works with messages with a length that is
 *      a multiple of the size of an 8-bit character.
 *
 */

#include <stdint.h>
#include <stdexcept>
#include <cstring>
#include "SHA1hashing.hpp"
#include "HashingStrategy.hpp"

SHA1hashing::SHA1hashing( void ) : HashingStrategy(20)
{
    std::memset(this->_message_block, 0, sizeof(this->_message_block));
    this->_length_low             = 0;
    this->_length_high            = 0;
    this->_message_block_index    = 0;
    this->_intermediate_hash[0]   = 0x67452301;
    this->_intermediate_hash[1]   = 0xEFCDAB89;
    this->_intermediate_hash[2]   = 0x98BADCFE;
    this->_intermediate_hash[3]   = 0x10325476;
    this->_intermediate_hash[4]   = 0xC3D2E1F0;
}

SHA1hashing::~SHA1hashing(void)
{
  
}

/*
 *  SHA1ProcessMessageBlock
 *
 *  Description:
 *      This function will process the next 512 bits of the message
 *      stored in the _message_block array.
 *
 *  Parameters:
 *      None.
 *
 *  Returns:
 *      Nothing.
 *
 *  Comments:
 *      Many of the variable names in this code, especially the
 *      single character names, were used because those were the
 *      names used in the publication.
 *
 */
void SHA1hashing::process_message_block(void)
{
  const uint32_t K[4] = {
    0x5A827999,
    0x6ED9EBA1,
    0x8F1BBCDC,
    0xCA62C1D6
  }; /* Constants defined in SHA-1 */

  int t;                  /* Loop counter         */
  uint32_t temp;          /* Temporary word value */
  uint32_t W[80];         /* Word sequence        */
  uint32_t A, B, C, D, E; /* Word buffers         */

  /*
   * Initialize the first 16 words in the array W
   */
  for(t = 0; t < 16; t++) {
    W[t] = this->_message_block[t * 4] << 24;
    W[t] |= this->_message_block[t * 4 + 1] << 16;
    W[t] |= this->_message_block[t * 4 + 2] << 8;
    W[t] |= this->_message_block[t * 4 + 3];
  }

  for(t = 16; t < 80; t++) {
    W[t] = rotate_left(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16],1);
  }
  
  A = this->_intermediate_hash[0];
  B = this->_intermediate_hash[1];
  C = this->_intermediate_hash[2];
  D = this->_intermediate_hash[3];
  E = this->_intermediate_hash[4];

  for(t = 0; t < 20; t++) {
    temp = rotate_left(A,5) + sha_ch(B,C,D) + E + W[t] + K[0];
    E = D;
    D = C;
    C = rotate_left(B,30);
    B = A;
    A = temp;
  }

  for(t = 20; t < 40; t++) {
    temp = rotate_left(A,5) + sha_parity(B,C,D) + E + W[t] + K[1];
    E = D;
    D = C;
    C = rotate_left(B,30);
    B = A;
    A = temp;
  }

  for(t = 40; t < 60; t++) {
    temp = rotate_left(A,5) + sha_maj(B,C,D) + E + W[t] + K[2];
    E = D;
    D = C;
    C = rotate_left(B,30);
    B = A;
    A = temp;
  }
  
  for(t = 60; t < 80; t++) {
    temp = rotate_left(A,5) + sha_parity(B,C,D) + E + W[t] + K[3];
    E = D;
    D = C;
    C = rotate_left(B,30);
    B = A;
    A = temp;
  }

  this->_intermediate_hash[0] += A;
  this->_intermediate_hash[1] += B;
  this->_intermediate_hash[2] += C;
  this->_intermediate_hash[3] += D;
  this->_intermediate_hash[4] += E;
  this->_message_block_index = 0;
}

/*
 *  SHA1PadMessage
 *
 *  Description:
 *      According to the standard, the message must be padded to an even
 *      512 bits.  The first padding bit must be a '1'.  The last 64
 *      bits represent the length of the original message.  All bits in
 *      between should be 0.  This function will pad the message
 *      according to those rules by filling the _message_block array
 *      accordingly.  It will also call the ProcessMessageBlock function
 *      provided appropriately.  When it returns, it can be assumed that
 *      the message digest has been computed.
 *
 *  Parameters:
 *      None.
 *      
 *  Returns:
 *      Nothing.
 *
 */
void SHA1hashing::pad_message(void)
{
  /*
   *  Check to see if the current message block is too small to hold
   *  the initial padding bits and length.  If so, we will pad the
   *  block, process it, and then continue padding into a second
   *  block.
   */
  if(this->_message_block_index > 55) {
    this->_message_block[this->_message_block_index++] = 0x80;
    
    while(this->_message_block_index < 64) {
      this->_message_block[this->_message_block_index++] = 0;
    }
    
    this->process_message_block();
    
    while(this->_message_block_index < 56) {
      this->_message_block[this->_message_block_index++] = 0;
    }
    
  } else {
    this->_message_block[this->_message_block_index++] = 0x80;
    
    while(this->_message_block_index < 56) {
      this->_message_block[this->_message_block_index++] = 0;
    }
  }
  
  /*
   * Store the message length as the last 8 bytes
   */
  this->_message_block[56] = this->_length_high >> 24;
  this->_message_block[57] = this->_length_high >> 16;
  this->_message_block[58] = this->_length_high >> 8;
  this->_message_block[59] = this->_length_high;
  this->_message_block[60] = this->_length_low >> 24;
  this->_message_block[61] = this->_length_low >> 16;
  this->_message_block[62] = this->_length_low >> 8;
  this->_message_block[63] = this->_length_low;
  
  this->process_message_block();
}

/*
 *  SHA1::process
 *
 *  Description:
 *      This function accepts an array of octets as the next portion
 *      of the message.
 *
 *  Parameters:
 *      context: [in/out]
 *          The SHA context to update
 *      message_array: [in]
 *          An array of characters representing the next portion of
 *          the message.
 *      length: [in]
 *          The length of the message in message_array
 *
 *  Returns:
 *      sha Error Code.
 *
 */

void SHA1hashing::process (const uint8_t *message_array, size_t length)
{
    if (this->final_state()) {
        throw std::logic_error ("SHA1hashing : you cannot process data while you have already finalized hashing");
    }

    if (this->is_corrupted()) {
        throw std::logic_error ("SHA1hashing : you cannot process data anymore, this hash is corrupted");
    }
    
    if (message_array == NULL) {
        throw std::invalid_argument ("SHA1hashing : array parameter is a null pointer");
    }
    
    if (length == 0) {
        return ;
    }

    while (length--) {
        this->_message_block[this->_message_block_index++] = (*message_array & 0xFF);
        
        this->add_length_to_context(8);
       
        if (this->_message_block_index == 64) {
            this->process_message_block();
        }

        message_array++;
    }
}


/*
 *  SHA1::getCheksum
 *
 *  Description:
 *      This function will return the 160-bit message digest into the
 *      Message_Digest array  provided by the caller.
 *      NOTE: The first octet of hash is stored in the 0th element,
 *            the last octet of hash in the 19th element.
 *
 *  Parameters:
 *      Message_Digest: [out]
 *          Where the digest is returned.
 *
 *  Exception:
 *      std::invalid_argument --> Message_Digest is NULL pointer.
 *      SHA1error             --> the message digest is corrupted (for more details,
 *                                refer to previous exception)
 *
 */
void SHA1hashing::finalize (void)
{
    if (this->is_corrupted()) {
        throw std::logic_error ("SHA1hashing : you cannot finalize hashing, this hash is corrupted");
    }

    if (!this->final_state()) {
        uint8_t digest[20];
        size_t i;

        this->pad_message();
        for(i=0; i<20; ++i) {
            digest[i] = this->_intermediate_hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) );
        }
        this->set_digest(digest, 20);

        // message may be sensitive, clear it out
        std::memset(this->_message_block, 0, sizeof(this->_message_block));
        // and clear length
        this->_length_low = 0;
        this->_length_high = 0;

        this->next_state();
    }
}

inline void SHA1hashing::add_length_to_context(size_t length)
{
    size_t tmp_length_low = this->_length_low;
    this->_length_low += length;

    // check overflow
    if (this->_length_low < tmp_length_low) {
        this->_length_high++;

        // check overflow, if so throw an exception
        if (this->_length_high == 0) {
            // Message is too long
            this->set_corrupted();
            throw std::logic_error ("SHA1hashing : input too long, message digest corrupted");
        }
    }
}

// (0 <= t <= 19)
inline uint32_t SHA1hashing::sha_ch( uint32_t a, uint32_t b, uint32_t c )
{
    return c ^ (a & (b ^ c));
}

// (20 <= t <= 39)
// (60 <= t <= 79)
inline uint32_t SHA1hashing::sha_parity( uint32_t a, uint32_t b, uint32_t c )
{
    return a ^ b ^ c;
}

// (40 <= t <= 59)
inline uint32_t SHA1hashing::sha_maj( uint32_t a, uint32_t b, uint32_t c )
{
    return (a & b) | (c & (a | b));
}

